package com.chenqi.myblog.controller;

import com.chenqi.myblog.model.Blog;
import com.chenqi.myblog.model.Tag;
import com.chenqi.myblog.service.BlogService;
import com.chenqi.myblog.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

/**
 * @description: 标签显示控制器
 * @program: myblog
 * @author: ChenQi
 * @create: 2021-02-2021/2/5-16-04
 */
@Controller
@RequestMapping("/tag")
public class TagController {

    @Autowired
    private TagService tagService;

    @Autowired
    private BlogService blogService;

    /**
     * 查看所有标签和对应标签的博客
     * @param tid
     * @param modelAndView
     * @return
     */
    @GetMapping("/list")
    public ModelAndView list(@RequestParam(value = "tid",required = false) Integer tid, ModelAndView modelAndView) {
        //标签id进行预处理
        tid = tid == null ? 1 : tid;
        List<Tag> allTag = tagService.findAllTag();
        List<Tag> newTags = new ArrayList<>();
        for (Tag tag : allTag) {
            List<Integer> tagIdByBlogId = tagService.findBlogIdsByTagId(tag.getId());
            tag.setTotal(tagIdByBlogId.size());
            newTags.add(tag);
        }
        List<Integer> tagIdByBlogId = tagService.findBlogIdsByTagId(tid);
        List<Blog> blogList = new ArrayList<>();
        for (Integer i : tagIdByBlogId) {
            Blog blog = blogService.findBlogById(i);
            blogList.add(blog);
        }

        modelAndView.addObject("tags", newTags);
        modelAndView.addObject("blogs", blogList);
        modelAndView.addObject("activeTagId", tid);
        modelAndView.setViewName("tags");
        return modelAndView;
    }
}
